<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use Swoole\Timer;
use App\Handlers\WeconHandler;
use Illuminate\Support\Facades\DB;

class GetWeconDataEveryMinute extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-wecon-data-every-minute';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command. 
     *
     * @return mixed
     */
    public function handle()
    {
        return; //废弃
        Timer::tick(60000, function (int $timer_id) {
            $cabinets = Cabinet::select('id', 'box_id', 'group_id')->where('box_id', '>', 0)->where('group_id', '>', 0)->get()->toArray();
            if ($cabinets) {
                $jsonArr = [];
                foreach ($cabinets as $oneCabinet) {
                    $wkData = WeconHandler::getRealtimeData($oneCabinet['box_id'], $oneCabinet['group_id']);
                    $backPoints = CabinetPoint::where('cabinet_id', $oneCabinet['id'])->pluck('alias')->toArray();
                    $insertData['cabinet_id'] = $oneCabinet['id'];
                    $insertData['created_time'] = time();
                    if (!$wkData) {
                        error_log("wkData = ".print_r($wkData,1)."\n",3,'/tmp/mmm.log');
                        error_log("oneCabinet = ".print_r($oneCabinet,1)."\n",3,'/tmp/mmm.log');
                        continue;
                    }
                    foreach ($wkData as $onePoint) {
                        $key = 'a_'.$onePoint['monitorId'];
                        if (in_array($key, $backPoints)) {
                            $jsonArr[$key] = floatval($onePoint['value']);
                        }
                    }
                    $insertData['data'] = json_encode($jsonArr);
                    DB::table('xfy_cabinet_data')->insert([$insertData]);
                }
            }  
        });
        \Swoole\Event::wait();
        return;
    }
}
